<?php

class LangStream {
    
	private
		$position = 0,
		$module = '';
		
	private static $aDTD = array ();
    
    public function stream_open($path, $mode, $options, &$opened_path) {
        $module = mb_substr (trim($path,'/'), 7);
        $this->module = $module;
    	
        if (empty (self::$aDTD[$module])) {
        	$this->buildDTDString ($module);
        }
 
        return true;
    }
    
    public function stream_read($count) {
        $ret = mb_substr (self::$aDTD[$this->module], $this->position, $count);
        $this->position += strlen($ret);
        
        return $ret;
    }
    
    public function stream_write($data){
       return false;
    }
    
    public function stream_tell() {
        return $this->position;
    }
    
    public function stream_eof() {
        return $this->position >= mb_strlen (self::$aDTD[$this->module]);
    }
    
    public function stream_seek($offset, $whence) {
        $l = mb_strlen (self::$aDTD[$this->module]);
        
        switch ($whence) {
            case SEEK_SET: $newPos = $offset; break;
            case SEEK_CUR: $newPos = $this->position + $offset; break;
            case SEEK_END: $newPos = $l + $offset; break;
            default: return false;
        }
        
        $ret = ($newPos >=0 && $newPos <= $l);
        
        if ($ret) {
        	$this->position = $newPos;
        }
        
        return $ret;
    }
    
    public function url_stat ($path, $flags) {
    	return array ();
    }
    
    private function buildDTDString ($module) {
    	self::$aDTD[$module] = '<?xml version="1.0" encoding="UTF-8"?>';
    	
	    $langFile = ENGINE_ROOT . '/modules/' . $module . '/i18n.' . LANG . '.php';
	
		if (file_exists ($langFile)) {
			include $langFile;
			
			if (!empty ($LANG) && is_array ($LANG)) {		
				foreach ($LANG as $key => $value) {
					if (mb_substr ($key, 0, 5) == 'label') {
						self::$aDTD[$module] .= "\r\n<!ENTITY " . $key . ' "' . $value . '">';
					}
				}
				
				unset ($LANG);
			}
		}
    }
}